package cn.itrip.dao;

import cn.itrip.common.Constants;
import cn.itrip.common.Page;
import cn.itrip.common.PropertiesUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.List;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2020/3/16 23:38
 * @Version: 1.0
 */
@Repository
public class BaseQuery<T> {

    private String url = PropertiesUtils.get("database.properties","baseUrl");
//    private String url = "http://localhost:8081/solr/hotel";
    private HttpSolrClient httpSolrClient;

    public BaseQuery(){
        httpSolrClient = new HttpSolrClient(url);
        httpSolrClient.setConnectionTimeout(1000);
        httpSolrClient.setParser(new XMLResponseParser());
    }

    /**
     * 分页查询
     */
    public Page<T> getHotelByPage(SolrQuery solrQuery,Integer pageNo,Integer pageSize,Class<T> clazz)
            throws IOException, SolrServerException {

        //设置分页
        if(pageNo == null) pageNo = Constants.DEFAULT_PAGE_NO;
        if(pageSize == null) pageSize = Constants.DEFAULT_PAGE_SIZE;
        solrQuery.setStart(pageSize*(pageNo-1));
        solrQuery.setRows(pageSize);

        //执行查询
        QueryResponse response = null;
        response = httpSolrClient.query(solrQuery);

        //解析数据
        //获得总页数，构建page对象
        //获得一个文档对象
        SolrDocumentList result = response.getResults();
        Integer total = (int)result.getNumFound();
        Page page = new Page(pageNo,pageSize,total);
        page.setRows(response.getBeans(clazz));
        return page;

    }

    /**
     * 根据排行分页
     */
    public List<T> getTop(SolrQuery solrQuery,Integer pageSize,Class<T> clazz)
            throws IOException, SolrServerException {
        //page == null ? null : page.getRows()
        return this.getHotelByPage(solrQuery,1,pageSize,clazz).getRows();


    }
}
